var json_clone = require('./util').json_clone;
var cache = require('./cache_redis').cache;
var _ = require('underscore');
var __slice = [].slice

exports.exclude_param = exclude_param =function(obj,params){
  var result = {};
  if(obj){
    result = json_clone(obj);
  }
  if(params){
    for(p in params){
      delete result[params[p]]
    }
  }
  return JSON.stringify(result);
}


exports.cache_json = cache_json = function(seconds,exclude_params,need_version){
  var version;
  var is_success_json = function(obj) {
    console.log(obj);
    if (typeof obj === "object") {
      if (obj.error) {
        return false;
      }
      if (typeof obj.error_no === "number" && obj.error_no !== 0) {
        return false;
      }
    }
    return true;
  }; 
  var format_obj = function(obj){
    if(!need_version){
      return obj;
    }
    if(_.isArray(obj)){
      var tmp_obj = {};
      tmp_obj.datas = obj;
      tmp_obj.version = new Date().getTime();
      // console.log(tmp_obj);
      return tmp_obj;
    }
    if(_.isObject(obj)){
      obj.version = new Date().getTime();
      return obj;
    }
    return obj;
  };

  var id;
  var memorize = function(fn, method) {
    return function() {
      var args, is_success_res, obj,i;

      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      if(this.statusCode === 200){
        i = args[0] == 200 ? 1 : 0;
        if(is_success_json(args[i])){
          args[i] = format_obj(args[i]);
          cache.save(id,args[i],seconds);
        }
      }
      if(version){
        args[i] = args[i].version;
      }
      return fn.apply(this, args);
    };
  };
  return function(req,res,next){
    version = req.param("version");
    var prefix = '';
    if(req.method != 'GET'){
      return next();
    }
    id = prefix + ':' + req.path + ':' + exclude_param(req.query,exclude_params) + ':' + exclude_param(req.params,exclude_params) + ':' + exclude_param(req.body,exclude_params);
    console.log(id);
    // console.log(id);
    cache.load(id,function(err,data){
      if(err){
        console.log("cache load error : " + err);
        return next();
      }
      if(data && (!req.param("refresh") || req.param("refresh") == "false")){
        console.log("from cache");
        if(version){
          return res.jsonp(data.version);
        }
        return res.jsonp(data);
      }

      res.json = memorize(res.json, "json");
      res.jsonp = memorize(res.jsonp, "jsonp");
      return next();
    })
  }
}